<template>
    <Dialog :app-dialog="appDialog">
        <div class="depart_box">
            <div class="depart_l">
                <el-input
                    v-model="searchName"
                    class="search_name"
                    placeholder="搜索成员、部门"
                    :prefix-icon="Search"
                    clearable
                    @input="handleSearch" />
                <el-button v-if="isExternal" style="margin-left: 20px" type="text" @click="getDepartList">
                    刷新页面
                </el-button>
                <el-tree-v2
                    ref="treeRef"
                    class="zw-tree-box"
                    :data="depart"
                    :props="defaultProps"
                    :filter-method="handleFilterMethod"
                    :height="400">
                    <template #default="{ node, data }">
                        <span v-if="isMember" class="custom-tree-node">
                            <span v-if="data.type == 'user' && !data.authorized && isDisableType == 1">
                                <el-checkbox
                                    v-model="data.check"
                                    :disabled="data.disabled"
                                    class="depart_member"
                                    @change="currentChange(data, node)">
                                    <span>
                                        <el-icon class="depart_member_icon">
                                            <user-filled />
                                        </el-icon>
                                        <el-tooltip
                                            effect="dark"
                                            :content="
                                                isQRAuth && !data.qr_code
                                                    ? '账号未授权获取二维码'
                                                    : '该员工需要先前往企业微信授权'
                                            "
                                            placement="top-start">
                                            <span>
                                                {{ node.label }}
                                                <span v-if="isLocal && data.is_local == 1">(本地)</span>
                                            </span>
                                        </el-tooltip>
                                    </span>
                                </el-checkbox>
                            </span>

                            <span v-else>
                                <el-checkbox
                                    v-if="data.type == 'user'"
                                    v-model="data.check"
                                    :disabled="data.disabled"
                                    class="depart_member"
                                    @change="currentChange(data, node)">
                                    <span>
                                        <el-icon class="depart_member_icon">
                                            <user-filled />
                                        </el-icon>
                                        <span>
                                            {{ node.label }} <span v-if="isLocal && data.is_local == 1">(本地) </span>
                                        </span>
                                    </span>
                                </el-checkbox>
                                <span v-else>
                                    <img class="depart_icon" src="/static/newDepart.png" alt="" />
                                    {{ node.label }}（{{ data.user_count || 0 }}）
                                </span>
                            </span>
                        </span>
                        <span v-else class="custom-tree-node">
                            <el-tooltip
                                v-if="data.type == 'user' && !data.authorized && isDisableType == '1'"
                                effect="dark"
                                content="该员工需要先前往企业微信授权"
                                placement="top-start">
                                <el-checkbox
                                    v-model="data.check"
                                    class="depart_member"
                                    :disabled="data.disabled"
                                    @change="currentChange(data, node)">
                                    <span>
                                        <el-icon class="depart_member_icon">
                                            <user-filled />
                                        </el-icon>
                                        <span>
                                            {{ node.label }} <span v-if="isLocal && data.is_local == 1">(本地)</span>
                                        </span>
                                    </span>
                                </el-checkbox>
                            </el-tooltip>
                            <span v-else>
                                <el-checkbox
                                    v-model="data.check"
                                    class="depart_member"
                                    :disabled="data.disabled"
                                    @change="currentChange(data, node)">
                                    <span>
                                        <el-icon v-if="data.type == 'user'" class="depart_member_icon">
                                            <user-filled />
                                        </el-icon>
                                        <img v-else class="depart_icon mr2" src="/static/newDepart.png" alt="" />
                                        <span>
                                            {{ node.label }}<span v-if="isLocal && data.is_local == 1">(本地)</span>
                                        </span>
                                        <span>{{ data.type == 'user' ? '' : `（${data.user_count || 0}）` }}</span>
                                    </span>
                                </el-checkbox>
                            </span>
                        </span>
                    </template>
                </el-tree-v2>
            </div>
            <div class="depart_r">
                <div class="depart_select_title">已选择的员工</div>
                <el-scrollbar height="380px">
                    <div v-for="item in selectedMember" :key="item.id" class="seled_member">
                        <div class="item_member">
                            <el-icon v-if="item.type == 'user'" class="seled_icon">
                                <user-filled />
                            </el-icon>
                            <img v-else class="depart_icon" src="/static/newDepart.png" alt="" />
                            <span class="member_name">
                                {{ item.name }}<span v-if="isLocal && item.is_local == 1">(本地)</span>
                            </span>
                        </div>
                        <el-icon class="remove_icon" @click="removeItem(item)">
                            <close />
                        </el-icon>
                    </div>
                </el-scrollbar>
            </div>
        </div>
    </Dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, watchEffect, computed, nextTick } from 'vue';
import Dialog from '@/components/Dialog.vue';
import { Search, UserFilled } from '@element-plus/icons-vue';
import type { ElTreeV2 } from 'element-plus';
import { getDepartUser } from '@/api/common';
import { useStore } from '@/store';
import { getSetionId } from '@/utils/utils';
import lodash from 'lodash';
const emit = defineEmits(['submit', 'submitDepart', 'determine']);
const store = useStore();
const treeRef = ref<InstanceType<typeof ElTreeV2>>();
// is_authorization默认为0由外部传入，0是可以勾选，1是可禁止勾选
// has_authorization默认为0由外部传入，0是默认查询全部，1是只查企微授权的
// is_sub_account 是否子账号
// unauthorized 是否经授权的账号
// qr_code 是否员工企微二维码
// status： 员工状态 1=已激活，2=已禁用， 4=未激活，5=退出企业
// authorized 授权状态： 员工手机号不为空、 并且非本地员工、并且员工的企微二维码不为空
const props = defineProps({
    is_authorization: {
        type: Number,
        default: 0
    },
    has_authorization: {
        type: Number,
        default: 0
    },
    type: Number,
    isLocal: {
        type: Boolean,
        default: false
    },
    unauthorized: {
        type: Boolean,
        default: false
    }
});

interface Tree {
    id: number;
    label: string;
    children?: Tree[];
}
interface Depart {
    departVisble: boolean;
    title?: string;
    creaters?: any[];
    isMember?: boolean;
}
// 部门信息
// 选中人员新】
const selectedMember = ref([]);
const disabledList = reactive<Array<any>>([]); // 不可选择的员工列表 id
const limit = ref('1'); //1为员工数据源 2 为开启会话存档和联系人权限的员工数据源
const newSelect = ref([]);
const mobile = ref('');
const disabledSelected = ref([]); // 禁用成员
const isDisableType = ref();
// 弹框
const departVisble = ref(false);
const isCancel = ref(false);
// 是否只支持人员信息
const isMember = ref(true);
// 是否只支持人员信息
const title = ref('部门人员信息');
const multiple = ref(true); //多选
const isExternal = ref(false); // 外部联系人
const isNotWxUser = ref(false); //是否绑定企微员工
const currentData = ref([]);
const isQRAuth = ref<boolean>(false); // 是否根据授权二维码显示提示内容
watch(
    () => props.type,
    val => {
        isDisableType.value = val;
    },
    { deep: true, immediate: true }
);
// 取消
const cancelHandel = () => {
    searchName.value = '';
    departVisble.value = false;
};
//确定
const submitHandel = () => {
    newSelect.value = [];
    isCancel.value = false;
    emit('submit', selectedMember.value, isCancel.value);
    emit('submitDepart', selectedMember.value, isCancel.value);
    emit('determine', selectedMember.value);
    departVisble.value = false;
    disabledSelected.value = [];
    isMember.value = true;
    searchName.value = '';
};
const appDialog = reactive({
    visible: departVisble,
    title: title,
    width: '800px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
});
const searchName = ref('');
const defaultProps = {
    children: 'children',
    label: 'name',
    value: 'd_u_unique_id'
};
const treeData: any[] = [];

const defaultExpandedKeys = reactive<any[]>([]);
const defaultExpandedLevel = 1; // 默认展开的层级
// 部门左侧树
const depart = ref([]);
// 获取部门员工信息
watchEffect(() => {
    if (departVisble.value) {
        getDepartList();
    }
});
// 获取部门成员信息
const getDepartList = async () => {
    // 部门ID department_id 1 Text  否
    // 外部联系人权限 is_wx_follow_user  默认 -1 全部 0 未开启 1 开启
    // 开启会话存档 is_open_session_archive  默认 -1 全部 0 未开启 1 开启
    //根据手机号查询员工信息
    const params = {
        department_id: '',
        is_wx_follow_user: -1,
        is_open_session_archive: -1,
        mobile: '',
        has_authorization: props.has_authorization
    };
    limit.value != '1' ? (params.is_open_session_archive = 1) : ''; // 开启会话存档
    isExternal.value ? (params.is_wx_follow_user = 1) : ''; //开启外部联系人
    params.mobile = mobile.value;
    const data: any[] = await getDepartUser(params);
    const ids = getSetionId('id', selectedMember.value);
    const resTreeData = filterMember(data, ids);
    treeData.splice(0, treeData.length, ...resTreeData);
    depart.value = resTreeData;
    treeRef.value!.setData(resTreeData);
    treeRef.value!.setExpandedKeys(defaultExpandedKeys); // 设置默认展开
};
// 过滤需要的人员信息
const filterMember = (data: any, ids?: any[], level = 1) => {
    data = Array.isArray(data) ? data : [data];
    const arr: any[] = [];
    data.forEach((item: any) => {
        item.level = level; // 添加层级
        // item.disabled = disabledSelected.value.includes(item.id)
        item.disabled = checkDisable(item);
        if (multiple.value) {
            item.check = ids.includes(item.id);
        } else {
            const ids = getSetionId('id', selectedMember.value);
            item.check = ids.includes(item.id);
        }
        if (item.users && item.users.length > 0) {
            item.members = item.users.length;
            if ((item.children && item.children.length == 0) || !item.children) {
                item.children = item.users;
            } else {
                item.children = Array.from(new Set([...item.children, ...item.users]));
            }
        }
        if (item.children && item.children.length > 0) {
            level <= defaultExpandedLevel && defaultExpandedKeys.push(item.d_u_unique_id); // 默认展开
            item.children = filterMember(item.children, ids, level + 1);
        }
        arr.push(item);
    });
    return arr;
};
// 各种禁用条件判断
// is_authorization默认为0由外部传入，0是可以勾选，1是可禁止勾选
// has_authorization默认为0由外部传入，0是默认查询全部，1是只查企微授权的
// is_sub_account 是否子账号
// unauthorized 是否经授权的账号
// qr_code 是否员工企微二维码
// status： 员工状态 1=已激活，2=已禁用， 4=未激活，5=退出企业
// authorized 授权状态： 员工手机号不为空、 并且非本地员工、并且员工的企微二维码不为空
const checkDisable = (item: any) => {
    const { id, type, authorized, is_sub_account, qr_code, status, is_wx_follow_user } = item;
    const disabled_1 = disabledSelected.value.includes(id);
    const disabled_2 = disabledList.some(ite => ite == id);
    if (isMember.value) {
        if (type == 'user' && !authorized && isDisableType.value == 1) {
            const disabled_3 = props.is_authorization == 1 ? is_sub_account : '';
            const disabled_4 = isQRAuth.value && !qr_code;
            const disabled_5 = status != 1;
            const disabled_6 = !authorized && !props.unauthorized;
            return disabled_2 || disabled_3 || disabled_4 || disabled_5 || disabled_6;
        } else {
            const disabled_3 = props.is_authorization == 1 ? is_sub_account : '';
            const disabled_4 = status != 1;
            const disabled_5 = !authorized && !props.unauthorized;
            const disabled_6 = isNotWxUser.value && is_wx_follow_user == 0;
            return disabled_1 || disabled_2 || disabled_3 || disabled_4 || disabled_5 || disabled_6;
        }
    } else {
        if (type == 'user' && !authorized && isDisableType.value == 1) {
            const disabled_3 = props.is_authorization == 1 ? is_sub_account : '';
            const disabled_4 = status != 1;
            const disabled_5 = !authorized;
            return disabled_2 || disabled_3 || disabled_4 || disabled_5;
        } else {
            return disabled_1 || disabled_2;
        }
    }
};

const current = ref();
const currentChange = (data: Tree, node: any) => {
    if (data.type == 'user') {
        seletData(data);
    }
    if (!isMember.value && data.type == 'department') {
        // data.children = childrenNode(data.check, data.children)
        // delete data.children
        // delete data.users
        seletData(data);
    }
    current.value = data;
    if (data.check) {
        currentData.value.push(data.id);
    } else {
        const index = currentData.value.findIndex((v: any) => v === data.id);
        currentData.value.splice(index, 1);
    }

    goRefreshTree(node);
};
// 刷新树列表组件
const goRefreshTree = (node: any) => {
    // 目前el组件无刷新的特定方案，暂且使用直接重新显式设置数据的方式来模拟刷新
    //（展开折叠的方式对滚动条位置有影响）暂不采用
    // $focureUpdate方法无效
    treeRef.value?.setData(treeData);
};
// 删除选中成员信息
const removeItem = (data: any) => {
    const result = selectedMember.value.filter((item: any) => item.id != data.id);
    selectedMember.value = result;
    depart.value = restoreDepart(data.id, depart.value, false);
    if (current.value?.check) {
        currentData.value.push(current.value.id);
    } else {
        const index = currentData.value.findIndex((v: any) => v === data.id);
        currentData.value.splice(index, 1);
    }
};
// 选中后放在右边的数据
const seletData = (item: any) => {
    // 多选
    if (multiple.value) {
        if (item.check) {
            selectedMember.value.push(item);
            newSelect.value.push(item);
        } else {
            if (selectedMember.value.length > 0) {
                selectedMember.value = selectedMember.value.filter((data: any) => item.id != data.id);
            }
        }
    } else {
        selectedMember.value = item.check ? [item] : [];
        newSelect.value = item.check ? [item] : [];
        filterMember(depart.value);
    }
};

// 自定义搜索
const handleSearch = lodash.debounce(() => {
    treeRef.value!.filter(searchName.value);
}, 500);
const handleFilterMethod = (query: string, node: any) => {
    return node.name!.includes(query);
};
//打开员工弹窗时，根据右边的数据确定左侧数的选中- val:true
// 删除右侧选中成员 恢复左边
const restoreDepart = (id: any, data: any, val?: any) => {
    return data.map((item: any) => {
        if (item.id == id) {
            item.check = val ? true : false;
        } else {
            if (item.children && item.children.length > 0) {
                item.children = val ? restoreDepart(id, item.children, true) : restoreDepart(id, item.children, false);
            }
        }
        return item;
    });
};
// 左侧树状态设置为false
const clean = (data: any) => {
    const arr: any[] = [];
    data.forEach((item: any) => {
        item.check = false;
        if (item.children && item.children.length > 0) {
            item.children = clean(item.children);
        }
        arr.push(item);
    });
    return arr;
};
const leftchecktree = (id?: any) => {
    depart.value = restoreDepart(id, depart.value, true);
};
// 查找部门的成员信息
const restore = (data: any) => {
    const arr: any[] = [];
    data.map((item: any) => {
        item.check = false;
        if (item.children && item.children.length > 0) {
            item.children = restore(item.children);
        }
        arr.push(item);
    });
    return arr;
};
defineExpose({
    departVisble,
    appDialog,
    title,
    leftchecktree,
    clean,
    depart,
    selectedMember,
    removeItem,
    isMember,
    disabledSelected,
    multiple,
    limit,
    mobile,
    isExternal,
    isNotWxUser,
    currentData,
    isQRAuth,
    disabledList
});
</script>
<style lang="scss" scoped>
.depart_box {
    display: flex;

    .depart_member_icon {
        vertical-align: bottom;
        margin-right: 2px;
    }

    .depart_icon {
        width: 15px;
        vertical-align: middle;
    }

    .mr2 {
        margin-right: 2px;
    }
}

.depart_l {
    width: 350px;
    padding-right: 10px;
    border-right: 1px solid #eaeaea;

    .search_name {
        // width: 259px;
        width: 100%;
        margin-bottom: 10px;
    }

    .custom-tree-node {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .is_member {
        // 不可全选样式
        :deep(.el-tree-node) {
            .is-leaf + .el-checkbox .el-checkbox__inner {
                display: inline-block;
            }

            .el-checkbox .el-checkbox__inner {
                display: none;
            }
        }
    }
}

.depart_r {
    padding: 10px 20px;
    flex: 1;

    .depart_select_title {
        margin-bottom: 20px;
    }

    .el-scrollbar {
        height: auto;
    }

    .seled_member {
        line-height: 30px;
        display: flex;
        font-size: 14px;
        padding: 0 5px;
        align-items: center;
        justify-content: space-between;

        &:hover {
            background-color: rgb(255 107 0 / 9.02%);
        }

        .item_member {
            display: flex;
            align-items: center;

            .seled_icon {
                color: #ff6b00;
            }
        }

        .member_name {
            margin-left: 2px;
        }

        .remove_icon {
            cursor: pointer;

            &:hover {
                transform: scale(1.23);
            }
        }
    }
}

:deep(.zw-tree-box) {
    .el-vl__wrapper {
        position: initial;
        overflow-x: scroll;

        .el-vl__window {
            width: 700px;
        }
    }
}
</style>
